package com.zking.handers;

import com.zking.entity.Customent;
import com.zking.repository.CustomentRepsitory;
import com.zking.util.CheckUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class UserHandler {
    private final CustomentRepsitory repsitory;

    public UserHandler(CustomentRepsitory repsitory){
        this.repsitory=repsitory;
    }
    /**
     * 得到所有用户
     * @param request
     * @return
     */
  public Mono<ServerResponse> getAllUser(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(this.repsitory.findAll(), Customent.class);
    }

    /**
     * 创建用户
     * @param request
     * @return
     */
    public Mono<ServerResponse> createUser(ServerRequest request){
        Mono<Customent> customentMono = request.bodyToMono(Customent.class);

        return customentMono.flatMap(u->{
            //校验代码需要放在这里
            CheckUtil.checkName(u.getName());
      return   ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(this.repsitory.saveAll(customentMono), Customent.class);
        });
    }


    /**
     * 更具id删除用户
     */
    public Mono<ServerResponse> deleteUser(ServerRequest request){
        String id = request.pathVariable("id");
        return this.repsitory.findById(Integer.valueOf(id)).flatMap(user->
                this.repsitory.delete(user).then(ServerResponse.ok().build()))
                .switchIfEmpty(ServerResponse.notFound().build());

    }
}
